package com.zzyy.study.base;

import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @auther zzyy
 * @create 2024-07-07 9:27
 */
public class DelayQueueDemo
{
    public static void main(String[] args) throws InterruptedException
    {
        //Class DelayQueue<E extends Delayed>
        BlockingQueue<Employee> blockingQueue = new DelayQueue<>();

        blockingQueue.put(new Employee("z3","doJava",2,TimeUnit.SECONDS));
        blockingQueue.put(new Employee("li4","doMysql",4,TimeUnit.SECONDS));
        blockingQueue.put(new Employee("w5","doFlink",1,TimeUnit.SECONDS));

        while(!blockingQueue.isEmpty())
        {
            System.out.println(blockingQueue.take());
        }
    }
}


/**
 * 延时对象，延时多少时间干活
 *
 */
@Setter
@Getter
@NoArgsConstructor
@AllArgsConstructor
class Employee implements Delayed
{
    private String name;
    private String task;
    private long   putTime = System.currentTimeMillis();//毫秒时间戳
    // 21:53:10   + 15 = 21:53:25
    private long   delayTime; //延时多少时间单位后触发任务动作,  actionTime = putTime + delayTime

    public Employee(String name, String task, long delayTime,TimeUnit timeUnit)
    {
        this.name = name;
        this.task = task;
        this.delayTime = TimeUnit.MILLISECONDS.convert(delayTime,timeUnit);
    }

    @Override
    public long getDelay(TimeUnit unit)
    {
        //零值或负值表示延迟已经过去
        return unit.convert((this.putTime + this.delayTime) - System.currentTimeMillis(),TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o)
    {
        return (int) (this.getDelay(TimeUnit.MILLISECONDS) - o.getDelay(TimeUnit.MILLISECONDS));
    }

    @Override
    public String toString()
    {
        return this.name+" ,mission is over,cost time: "+this.delayTime +" milliseconds";

    }
}

